package com.sanqing.action;

import java.io.PrintWriter;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.sanqing.dao.DepartmentDao;
import com.sanqing.dao.PositionDao;
import com.sanqing.po.Department;
import com.sanqing.po.Position;

public class AjaxAction extends DispatchAction {
	public ActionForward getDepts(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int act = Integer.parseInt(request.getParameter("act"));
		DepartmentDao deptDao = new DepartmentDao();
		List depts = deptDao.findAll();
		if(act==1){
			Iterator it = depts.iterator();
			while(it.hasNext()){
				Department dept = (Department)it.next();
				if(dept.getRecruitments()!=null&&dept.getRecruitments().size()<=0){
					it.remove();
				}
			}
		}
		response.setCharacterEncoding("utf-8");  
		try{
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			Iterator it = depts.iterator();
			while(it.hasNext()){
				Department dept = (Department)it.next();
				JSONObject obj = new JSONObject();
				obj.put("id", dept.getId());
				obj.put("name",dept.getName());
				jsonArray.add(obj);
			}
			jsonObject.put("jsonArray", jsonArray);
			//System.out.print(jsonObject.toString());
			out.write(jsonObject.toString());
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
	public ActionForward getPositions(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		int deptId = Integer.parseInt(request.getParameter("deptId"));
		Collection positions = null;
		if(deptId<0){
			PositionDao posiDao = new PositionDao();
			positions = posiDao.findAll();
		}
		else{
			DepartmentDao deptDao = new DepartmentDao();
			positions = deptDao.findById(deptId).getPositions();
		}
		response.setContentType("text/html; charset=utf-8");  
		try{
			PrintWriter out = response.getWriter();
			JSONObject jsonObject = new JSONObject();
			JSONArray jsonArray = new JSONArray();
			Iterator it = positions.iterator();
			while(it.hasNext()){
				Position position = (Position)it.next();
				JSONObject obj = new JSONObject();
				obj.put("id", position.getId());
				obj.put("name",position.getName());
				jsonArray.add(obj);
			}
			jsonObject.put("jsonArray", jsonArray);
			out.print(jsonObject.toString());
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}
}
